package pers.liyan.shi.springclouddistributedlocker.task;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * 使用zookeeper实现分布式锁-测试,
 * 测试多个实例同时执行定时任务
 *
 * @author ShiLY
 * @version 1.0
 * @date 2020/2/23 12:56
 */
@Slf4j
@Component
public class ZKLockerTest {

    private final InterProcessMutex interProcessMutex;

    private final Environment environment;

    public ZKLockerTest(Environment environment, InterProcessMutex interProcessMutex) {
        this.environment = environment;
        this.interProcessMutex = interProcessMutex;
    }

    //@Scheduled(cron = "0/20 * * * * ? ")
    public void execute() {
        try {
            boolean acquire = interProcessMutex.acquire(1, TimeUnit.SECONDS);
            if (acquire) {
                log.info("execute task, env={}", Arrays.toString(environment.getActiveProfiles()));
                Thread.sleep(5000);
                interProcessMutex.release();
            }
        } catch (Exception e) {
            log.error("schedule task error", e);
        }

    }

}
